package org.jtorrent.connection;

import org.jtorrent.torrent.TorrentData;
import org.jtorrent.Constants;

import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;

/**
 * Ryan Thomas
 * r.n.thomas@gmail.com
 *
 * @author ryan
 * @version $Revision$ $Author$ $Date$
 * @since Jun 21, 2009
 */
public class ConnectionManager {
    /** Torrent metafile info */
    private TorrentData data;

    /** A 20 byte string used as a unique identifier for this peer */
    private byte[] peedId;

    /** A port in the range 6881 - 6889 */
    private int port;
    
    /** The number of peers to request from the tracker */
    private int peerRequestCount;

    /**
     * Create a new connection manager for getting request data from the tracker
     *
     * @param data The torrent metafile
     * @param peerId A 20 byte unique peer id
     * @param port A port in the range 6881 - 6889 (BitTorrent spec)
     * @param peerRequestCount The number of peers to request from the tracker
     */
    public ConnectionManager(final TorrentData data,
                             final byte[] peerId,
                             final int port,
                             final int peerRequestCount) {
        this.data = data;
        this.peedId = peerId;
        this.port = port;
        this.peerRequestCount = peerRequestCount;

        if(peerId.length != 20) {
            throw new IllegalArgumentException("peerId parameter must be 20 bytes long");
        }
    }

    public String buildUrl() throws ConnectionException {
        StringBuffer url = new StringBuffer();
        url.append(data.getAnnounceUrl());
        url.append("?");
        url.append(Constants.TRACKER_INFO_HASH);
        url.append("=");

        url.append(encodeInfoHash());

        //todo: the rest of the url...

        return url.toString();
    }

    public String encodeInfoHash() throws ConnectionException {
        try {
            return URLEncoder.encode(new String(data.computeInfoHash()), "UTF-8");
        }
        catch(UnsupportedEncodingException e) {
            throw new ConnectionException(e);
        }
        catch(NoSuchAlgorithmException e) {
            throw new ConnectionException(e);
        }
    }
}
